package com.pv.user.service.impl;

import com.pv.common.utils.R;
import com.pv.user.common.RedisConstant;
import com.pv.user.feign.ThirdPartyFeignService;
import com.pv.user.service.SmsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: Zk
 * @Date: 2021/8/26 9:31
 */
@Log4j2
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    /**
     * 短信验证码有效期（单位：分钟）
     */
    @Value("${sms.expire-minute:5}")
    private Integer expireMinute;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean sendSmsCode(String phone){
        String uuid = UUID.randomUUID().toString().replace("-","");
        String code =uuid.substring(0, 6);
        stringRedisTemplate.opsForValue().set(RedisConstant.SMS+phone, code, expireMinute,
                TimeUnit.MINUTES);
        R p = thirdPartyFeignService.Phone(phone, code);
        if (p.getCode() == 0){
            return true;
        }else {
            return false;
        }
    }
    @Override
    public boolean matcheCodeAndGetPhone(String phone, String code) {
        String value = stringRedisTemplate.opsForValue().get(RedisConstant.SMS+phone);
        if (value != null && value.equals(code)) {
            log.info("验证码校验成功：{}", value);
            stringRedisTemplate.delete(RedisConstant.SMS+phone);
            return true;
        }
        return false;
    }
}
